#include "SSD1306Wire.h"
#include "DHT.h"
#include <string>
#include<sstream>
/* 设置oled屏幕的相关信息 */
//const int I2C_ADDR = 0x3C;              // oled屏幕的I2c地址
const int I2D_ADDR = 0x3C;              // oled屏幕的I2c地址
#define SDA_PIN_1 4                       // SDA引脚，默认gpio4(D2)
#define SCL_PIN_1 5                       // SCL引脚，默认gpio5(D1)

#define DHTPIN 12                       // SDA引脚，默认gpio4(D6)

#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
/* 新建一个oled屏幕对象，需要输入IIC地址，SDA和SCL引脚号 */
SSD1306Wire oled1(I2D_ADDR, SDA_PIN_1, SCL_PIN_1);

//SSD1306Wire oled2(I2C_ADDR, SDA_PIN_2, SCL_PIN_2);
void setup() {
  /* 1. 初始化串口通讯波特率为115200*/
  Serial.begin(115200);
  //湿度监测物理端口
  pinMode(A0, INPUT);

  //D0继电器端口
  pinMode(D0, OUTPUT);
  /* 2. oled屏幕初始化 */
  oled1.init();
  oled1.flipScreenVertically();        // 设置屏幕翻转

  oled1.setContrast(255);              // 设置屏幕亮度
  drawRect();                         // 测试屏幕显示
  oled1.clear();
  oled1.display();       // 清除屏幕
  dht.begin();
}

void loop() {
  int  knockVal = analogRead(A0); //获取湿度数值
  String ss; 
  if (knockVal > 500) //湿度大于500 打开继电器
  {
    digitalWrite(D0, HIGH);
    ss = "o";
  } else
  {
    digitalWrite(D0, LOW);
    ss = "c";
  }

  oled1.setFont(ArialMT_Plain_24);    // 设置字体
  oled1.setTextAlignment(TEXT_ALIGN_LEFT);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float hic = dht.computeHeatIndex(t, h, false);

  String hs = String(h);
  int i = hs.indexOf(".");
  String h1 = hs.substring(0, i);

  String hics = String(hic);
  int j = hics.indexOf(".");
  String hic1 = hics.substring(0, j);
  String hy = String(knockVal);

  String m1 = "H:" + h1 + "%  " + hy;
  String m2 = "T:" + hic1 + "°C   "+ ss;
  oled1.drawString(0, 0, m1);
  oled1.drawString(1, 30, m2);
  oled1.setFont(ArialMT_Plain_16);
  oled1.drawString(0, 70, hy);

  oled1.display();                     // 将缓存里的文字在屏幕上显示
  delay(1000);
  oled1.clear();
}

void drawRect(void) {
  for (int16_t i = 0; i < oled1.getHeight() / 2; i += 2) {
    oled1.drawRect(i, i, oled1.getWidth() - 2 * i, oled1.getHeight() - 2 * i);
    oled1.display();
    delay(50);
  }
}